import java.util.ArrayList;
import java.util.List;

public class Solution637 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list=new ArrayList<>();
        List<Integer> count=new ArrayList<>();
        dfs(0,root,list,count);
        return list;
    }

    private void dfs(int k, TreeNode root, List<Double> list, List<Integer> count) {
        if (root==null){
            return;
        }
        if (k==list.size()){
            list.add(root.val*1.0);
            count.add(1);
        }else{
            list.set(k,(list.get(k)*count.get(k)+root.val)/(count.get(k)+1));
            count.set(k,count.get(k)+1);
        }
        dfs(k+1,root.left,list,count);
        dfs(k+1,root.right,list,count);
    }

    public static void main(String[] args) {
        System.out.println(new Solution637().averageOfLevels(new TreeNode(3,new TreeNode(9),new TreeNode(20,new TreeNode(15),new TreeNode(7)))));
    }
}
